import json
import difflib
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# import webbrowser

def compare_files(file1_path, file2_path):
    # 读取文件内容
    with open(file1_path, "r", encoding="utf-8") as file1, open(file2_path, "r", encoding="utf-8") as file2:
        file1_lines = file1.readlines()
        file2_lines = file2.readlines()

    # 使用 difflib 比较差异
    diff = difflib.Differ()
    diff_result = list(diff.compare(file1_lines, file2_lines))

    # 提取变化的部分
    changes = []
    file1_line_num = 1
    file2_line_num = 1

    for line in diff_result:
        if line.startswith("- "):
            changes.append(f"{file1_line_num}: {line.strip()}")
            file1_line_num += 1
        elif line.startswith("+ "):
            changes.append(f"{file2_line_num}: {line.strip()}")
            file2_line_num += 1
        else:
            file1_line_num += 1
            file2_line_num += 1

    # 将变化部分格式化为HTML
    html_changes = "<h2>文件变化部分</h2><pre>"
    for change in changes:
        if "- " in change:
            html_changes += f"<span style='color:red;'>{change}</span><br>"
        elif "+" in change:
            html_changes += f"<span style='color:green;'>{change}</span><br>"
    html_changes += "</pre>"

    return html_changes
    
def send_email(html_content, to_email, subject="File Comparison Result"):
    # 邮件服务器配置
    smtp_server = "smtp.qq.com"  # 替换为你的SMTP服务器
    smtp_port = 587  # 替换为你的SMTP端口
    smtp_user = "291695377@qq.com"  # 替换为你的邮箱
    smtp_password = "bhecyaqfyhodbiia"  # 替换为你的邮箱密码

    # 创建邮件对象
    msg = MIMEMultipart()
    msg["From"] = smtp_user
    msg["To"] = to_email
    msg["Subject"] = subject
    print('html_content',html_content)
    # 添加 HTML 内容
    html_part = MIMEText(html_content, "html")
    msg.attach(html_part)

    # 发送邮件
    try:
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()  # 启用TLS加密
            server.login(smtp_user, smtp_password)
            server.sendmail(smtp_user, to_email, msg.as_string())
        print("邮件已成功发送到", to_email)
    except Exception as e:
        print("发送邮件时出错:", e)

def load_cfg(file):
    with open(file, "r", encoding="utf-8") as f:
        return json.load(f)

def main():
    obj = load_cfg("setting.json")
    print(obj)
    for watch in obj["watchs"]:
        print(watch)
        print(watch["url"])
        # print(watch["interval"])
        
    htmlstr = compare_files("file1.txt", "file2.txt")
    # send_email(htmlstr, "291695377@qq.com" , "网页变化")

if __name__ == "__main__":
    main()